<template>
  <a-card :bordered="false">

    <!-- 左侧面板 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="12">
          <a-col :md="4" :sm="8">
            <a-form-item label="聚合码ID" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 1 }">
              <a-input v-model="queryParam.id" placeholder="请输入聚合码ID" allowClear onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" />
              <!-- <a-input-number id="inputNumber" v-model="queryParam.id" :min="0" placeholder="请输入聚合码ID" style="width:100%"/> -->
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="聚合码名称" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 1 }">
              <a-input placeholder="请输入聚合码名称" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="适用小程序" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 1 }">
              <a-select v-model="queryParam.brandId" placeholder="请选择" show-search allowClear>
                <a-select-option :value="item.id.toString()" v-for="item in departList" :key="item.id"> {{ item.brandName }} </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="状态" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 1 }">
              <a-select v-model="queryParam.status" placeholder="请选择" default-value="null"
                :getPopupContainer="triggerNode => triggerNode.parentNode">
                <!-- <a-select-option value="0">全部</a-select-option> -->
                <a-select-option value="0">启用</a-select-option>
                <a-select-option value="1">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" icon="search" @click="searchQuery">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a-button type="primary" @click="toDrcode" style="margin-left: 8px">多人码管理</a-button>
              <a-button type="primary" @click="toJhcodeset('xz')" style="margin-left: 8px">新建聚合码</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
      <!-- <div class="table-operator" style="border-top: 5px">
      <a-button type="primary" icon="download" @click="handleExportXls('订单明细')">导出</a-button>
    </div> -->
      <a-table ref="table" rowKey="id" :scroll="{ x: 1500 }" size="middle" :columns="columns" :dataSource="dataSource"
        :loading="loading" :pagination="ipagination" @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a-popconfirm @confirm="() => handleStatus(record)">
            <template slot="title">
              <p>确认要{{ record.statusText == '启用' ? '禁用' : record.statusText == '禁用' ? '启用' : '' }}该聚合码吗？</p>
              <p class="titlell" v-if="record.statusText == '禁用'">请确保已和业务部门沟通一致</p>
              <p class="titlell" v-if="record.statusText == '启用'">禁用后已使用该聚合码的场景将失效，请仔细确认</p>
            </template>
            <a>{{ record.statusText =='启用' ? '禁用' : record.statusText == '禁用' ? '启用' : '' }}</a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a @click="toJhcodeset(record,'bj')"> 编辑</a>
          <a-divider type="vertical" />
          <a @click="toJhcodeset(record)"> 复制</a>
          <a-divider type="vertical" />
          <a @click="handleTf(record, 'tf')">投放</a>
          <a-divider type="vertical" />
          <a @click="handleTf(record, 'yycj')">应用场景</a>
          <a-divider type="vertical" v-if="record.status == 1"/>
          <a-popconfirm @confirm="() => handleDelete(record.id)" v-if="record.status == 1">
            <template slot="title">
              <p>确认要删除该聚合码吗？</p>
              <p class="titlell">请和业务仔细确认后再删除</p>
            </template>
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <!-- 下载中心 -->
    <a-modal v-model="visible" title="下载中心" @ok="handleOk" width="1000px">
      <!-- <div class="downloadTitle">下载中心</div> -->
      <a-table 
        :columns="downcolumns" 
        :data-source="downloadSource"  
        :pagination="downloadipag"
        :loading="loading"
        @change="handleTableChange1"
       >
        <span slot="action" slot-scope="text, record">
          <a @click="dfLoad(record)" :disabled="record.status !== 1 || record.url == ''" v-if="record.type == 1">
            <a-icon type="edit"/>
            下载
          </a>
          <a :disabled="record.status !== 1 || record.url == ''" v-else @click="downloadIamge(record.url,record.name)">
            <a-icon type="edit"/>
            下载
          </a>
        </span>
      </a-table>
    </a-modal>
    <!-- 下载icon -->
    <img src="https://img.bzhz.jnbygroup.com/dincandownload.png" alt="" class="download" @click="downloadicon">
    <!-- 查看二维码 -->
    <a-modal title="二维码" :dialog-style="{ top: '200px' }" :visible="removeVisible" @ok="clickCode()" okText="下载"  @cancel="() => (removeVisible = false)">
      <img
        style="width: 200px;height:200px;margin-left: 129px;"
        :src="qrCode"
      />
    </a-modal>
    <toufang ref='modalForm'></toufang>
  </a-card>
</template>
<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import toufang from './jhcode/modules/toufang.vue'
import { filterObj } from '@/utils/util';
import { getAction } from '@/api/manage'
import { saveOrUpdateGather,brandList,delGatherById,pageDownloadVo} from '@/api/marketingCenter/code'
export default {
  mixins: [JeecgListMixin],
  components: { toufang },
  data() {
    return {
      visible:false,
      removeVisible: false,
      qrCode:'',
      downcolumns:[
        {
          title: '任务名称',
          align: "center",
          dataIndex: 'name',
        },
        {
          title: '下载时间',
          align: "center",
          dataIndex: 'createTime',
        },
        {
          title: '文件大小',
          align: "center",
          dataIndex: 'fileSize',
        },
        {
          title: '下载状态',
          align: "center",
          dataIndex: 'statusText',
        },
        {
          title: '操作',
          align: "center",
          dataIndex: 'action',
          scopedSlots: {customRender: 'action'},
        }
      ],
      downloadSource:[],
      downloadipag:{
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['2', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        total: 0
      },
      description: '这是数据字典页面',
      visible: false,
      // 查询条件
      queryParam: {},
      dataSource: [
        { status: 1,
           payStatusText: "禁用", 
           url: "https://img.bzhz.jnbygroup.com/FvAA136wg0kEEqIb14DHOb22sbi4", 
           list: [{nickName:'hhh'}] 
          }
        ],
      // 表头
      columns: [
        // {
        //   title: '序号',
        //   dataIndex: '',
        //   key: 'rowIndex',
        //   width: 120,
        //   align: "center",
        //   customRender: function (t, r, index) {
        //     return parseInt(index) + 1;
        //   }
        // },
        {
          title: '聚合码ID',
          align: "center",
          dataIndex: 'id',
        },
        {
          title: '聚合码名称',
          align: "center",
          dataIndex: 'name',
        },
        {
          title: '适用小程序',
          align: "center",
          dataIndex: 'brandName',
        },
        {
          title: '备注',
          align: "center",
          dataIndex: 'remark',
        },
        {
          title: '聚合码规则',
          align: "center",
          dataIndex: 'ruleName',
          customRender: function(ruleName){
            return <span style="white-space: pre-line;">{ruleName}</span>
          }

        },
        {
          title: '状态',
          align: "center",
          dataIndex: 'statusText',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: { customRender: 'action' },
          fixed: 'right',
          width: 350
        }
      ],
      dict: "",
      labelCol: {
        xs: { span: 8 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 16 },
        sm: { span: 19 },
      },
      url: {
        list: "/backend/qrcode/pageGatherVo",
      },
      departList: [],//适用小程序
      storeId: "",
    }
  },
  computed: {
  },
  watch: {},
  created() {
    // 获取适用小程序下拉选
    this.getBrandId()
  },
  mounted() {
  },
  methods: {
    // 下载二维码zip
    dfLoad(file) {
      this.getBlob(file.url).then(blob => {
         this.DownloadItem(blob, file.name);
     });
   },
   getBlob(url) {
    return new Promise(resolve => {
     const xhr = new XMLHttpRequest();
     xhr.open('GET', url, true);
     xhr.responseType = 'blob';
     xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
},
DownloadItem(blob,fileName){
         let link = document.createElement('a');
         link.href = window.URL.createObjectURL(blob);
         link.download = fileName;
         link.click();
    },
    //删除
    handleDelete(id){
      delGatherById({id: id}).then((res) => {
        if (res.success) {
          // //重新计算分页问题
          // that.reCalculatePage(1)
          this.$message.success(res.message || res.msg);
          this.loadData();
        } else {
          this.$message.warning(res.message || res.msg);
        }
      });
    },
    //启用禁用
    handleStatus(record){
      console.log(record);
      var status={
        id:record.id,
        status:record.status==0?1:0,
        statusText:record.statusText=='启用'?'禁用':record.statusText=='禁用'?'启用':'',
      }
      saveOrUpdateGather(status).then(res=>{
        if(res.code==200){
          this.loadData();
        }
      })
    },
    handleTf(record, type) {
      this.$refs.modalForm.edit(record, type);
      this.$refs.modalForm.disableSubmit = true;
    },
    storeIdChange(el) {
      this.queryParam.storeId = el
    },
    getQueryParams() {
      var param = Object.assign(this.queryParam);
      param.current = this.ipagination.current;
      param.size = this.ipagination.pageSize;
      return filterObj(param);
    },
    //获取适用小程序下拉
    getBrandId(){
      brandList().then(res=>{
        if(res.code==200){
          this.departList=res.data
        }
      })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    toDrcode(record) {
      // this.$router.push(`/marketingCenter/code/jhcode/drcode/${record.id}`)
      this.$router.push(`/marketingCenter/code/jhcode/drcode`)
    },
    toJhcodeset(record,type) {
      this.$router.push(`/marketingCenter/code/jhcode/jhcodeset/id=${record.id}=${type}`)
      // this.$router.push(`/marketingCenter/code/jhcode/jhcodeset`)
    },
    // 重置字典类型搜索框的内容
    searchReset() {
      var that = this;
      that.queryParam = {}
      that.loadData(this.ipagination.current);
    },
    handleTableChange1(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination,'1111')
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.downloadipag.pageSize = pagination.pageSize;
      this.downloadipag.current = pagination.current;
      this.downloadicon()
    },
    downloadicon() {
      console.log('下载icon');
      pageDownloadVo({
        current:this.downloadipag.current,
        size:this.downloadipag.pageSize
      }).then(res => {
        console.log(res);
        if(res.code == 200) {
          this.downloadSource = res.data.records
          this.downloadipag.pageSize = res.data.size
          this.downloadipag.total = res.data.total
        }
      })
      this.visible = true
    },
    clickCode() {
      console.log('下载');
      this.removeVisible = false
      this.downloadIamge(this.qrCode, '二维码');
    },
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function() {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");

        var a = document.createElement("a");
        var event = new MouseEvent("click");
        a.download = name || "photo";
        a.href = url; 
        a.dispatchEvent(event);
      };
      image.src = imgsrc;
    },
    handleOk() {
      this.visible = false;
    },
  },
}
</script>
<style scoped lang="less">
.titlell {
  font-size: 12px;
}
.download {
    width: 45px;
    height: 45px;
    position: absolute;
    bottom: 0px;
    right: 15px;
    cursor:pointer;
  }
</style>